import decimal

import scrapy

from apps.tender_project.tender_project.utils.date import DateMixIn
from components.custom_item import UpdateCustomItem
from utils.tools import *


class NetTenderInfoItem(UpdateCustomItem):
    """
    项目招标信息
    """
    __table_name__ = "net_tender_info"

    __unique_key__ = [
        "project_name",
        "register_num",
        "project_desc",
        "budget_amount",
        "max_price",
        "buying_require",
        "accept_combo",
        "bidder_qualification",
        "leader_qualification",
        "other_qualification",
        "deadline",
        "open_time",
        "buying_type",
        "buying_name",
        "buying_tel",
        "contact_name",
        "contact_tel",
        "agency",
        "agency_tel",
    ]
    province = scrapy.Field()  # 省
    city = scrapy.Field()  # 市
    region = scrapy.Field()  # 区、县
    title = scrapy.Field()  # 公告标题
    get_date = scrapy.Field()  # '发布时间
    data_type = scrapy.Field()  # 数据类型(意见征集、招标公告、重新招标、答疑公告、信息变更、招标预告...)
    project_name = scrapy.Field()  # 项目名称
    register_num = scrapy.Field()  # 项目编号
    project_desc = scrapy.Field()  # 项目描述 json_object {"content":"详情"}
    budget_amount = scrapy.Field()  # 预算金额(万元)
    max_price = scrapy.Field()  # 最高限价(万元)
    buying_require = scrapy.Field()  # 采购需求 json_object {"content":"采购需求"}
    accept_combo = scrapy.Field()  # 项目接受联合体投标
    bidder_qualification = scrapy.Field()  # 普通资格要求 json_object {"content":"采购需求"}
    leader_qualification = scrapy.Field()  # 项目经理资格要求 json_object {"content":"项目经理资格要求"}
    other_qualification = scrapy.Field()  # 项目特定资格要求 json_object {"content":"项目特定资格要求"}
    deadline = scrapy.Field()  # 截止时间
    open_time = scrapy.Field()  # 开标时间
    buying_type = scrapy.Field()  # 采购方式(竞争性磋商、竞争性谈判、公开招标)
    buying_name = scrapy.Field()  # 采购方名称
    buying_tel = scrapy.Field()  # 采购方联系方式
    contact_name = scrapy.Field()  # 项目联系联系人
    contact_tel = scrapy.Field()  # 项目联系人电话
    agency = scrapy.Field()  # 采购执行机构名称
    agency_tel = scrapy.Field()  # 采购执行机构联系方式
    source = scrapy.Field()  # '来源平台
    source_url = scrapy.Field()  # '来源平台链接

    def pre_to_db(self):
        # json 化字段
        for k in [
            "project_desc",
            "buying_require",
            "bidder_qualification",
            "leader_qualification",
            "other_qualification",
        ]:
            if self[k]:
                if not isinstance(self[k], dict):
                    self[k] = {"content": self[k]}
            else:
                self[k] = None
        # 处理金额字段
        for k in [
            "budget_amount",
            "max_price",
        ]:
            if self[k]:
                if not isinstance(self[k], (float, int, decimal.Decimal)):
                    self[k] = PriceMixIn.process_money(self[k])
            else:
                self[k] = None

        # 处理日期字段
        for k in [
            "deadline",
            "open_time",
        ]:
            if self[k]:
                self[k] = DateMixIn.process_date(self[k])
            else:
                self[k] = None

        if self.buying_name:
            self.buying_name = re.sub(r"(?:.{0,3}[:：]+)", "", self.buying_name)


class NetProjectInfoItem(UpdateCustomItem):
    """
    项目中标信息
    """
    __table_name__ = "net_project_info"

    province = scrapy.Field()  # 省
    city = scrapy.Field()  # 市
    region = scrapy.Field()  # 区、县
    title = scrapy.Field()  # 公告标题
    get_date = scrapy.Field()  # '发布时间
    data_type = scrapy.Field()  # 数据类型(开标公示、中标公示、候选人公示、废标公示...)
    project_date = scrapy.Field()  # 中标时间
    project_name = scrapy.Field()  # 项目名称
    register_num = scrapy.Field()  # 项目编号
    budget_amount = scrapy.Field()  # 预算金额(万元)
    project_company_info = scrapy.Field()  # 中标单位信息(需要英文键,保证查询) json_array [{"com_name": "中标公司","price": "中标金额(万元)","ar_name":"建造师","candidate":"1第一中标 2第二中标 3第三中标","address":"地址", "duration":"工期"}]
    project_info = scrapy.Field()  # 中标标的信息(需要英文键,保证查询) json_array [{"project_name":"主要投标标的名称","term":"服务期限", "people_num":"服务团队人数", "brand":"品牌", "model":"规格型号", "num":"数量", "desc":"服务要求或者标的基本概况","ar_name":"拟派项目经理", "price":"单价"}]
    project_refuse_info = scrapy.Field()  # 未过审单位信息(各个包的投标人名称+未过审原因) json_array [{"com_name": "投标人名称", "reason":"被拒绝原因","detail":"招标文件相应拒绝条款"}]
    review_names = scrapy.Field()  # 评审人员
    source = scrapy.Field()  # 来源平台
    source_url = scrapy.Field()  # '来源平台链接

    __unique_key__ = [
        "province",
        "city",
        "region",
        "title",
        "get_date",
        "data_type",
        "project_date",
        "project_name",
        "register_num",
        "budget_amount",
        "project_company_info",
        "project_info",
        "project_refuse_info",
        "review_names",
        "source",
        "source_url",
    ]

    def pre_to_db(self):
        # 处理金额字段
        for k in [
            "budget_amount",
        ]:
            if self[k]:
                if not isinstance(self[k], (float, int, decimal.Decimal)):
                    self[k] = PriceMixIn.process_money(self[k])
            else:
                self[k] = None

        if self.project_company_info:
            tmp_project_company_info = []
            for i in self.project_company_info:
                if i.get("price"):
                    if not isinstance(i.get("price"), (float, int, decimal.Decimal)):
                        i = {**i, **{"price": PriceMixIn.process_money(i.get("price"))}}
                tmp_project_company_info.append(i)
            self.data_type = "中标成交公告"
            self.project_company_info = tmp_project_company_info

        self.get_date = DateMixIn.process_date(self.get_date)
        self.project_date = DateMixIn.process_date(self.project_date)
